package org.example.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;

@Slf4j
@Controller
public class Client1Controller {

    @Value("${sso.server.url:http://localhost:8080}")
    private String ssoServerUrl;
    private String clientId = "app1";
    private String redirectUri = "http://localhost:8081/callback";

    // 客户端首页（需要登录）
    @GetMapping("/")
    public String index(HttpServletRequest request, Model model) {
        log.info("跳转到客户端1首页");

        // 从会话里取出token
        String token = (String) request.getSession().getAttribute("token");
        token = token == null ? request.getParameter("token") : token;
        log.info("客户端1-从会话中获取token: {}", token);
        if (token == null) {
            // 未登录，跳转到SSO认证中心
            return "redirect:" + ssoServerUrl + "/login?clientId=" + clientId + "&redirectUri=" + redirectUri;
        }

        // 验证令牌有效性
        boolean valid = validateToken(token);
        if (!valid) {
            request.getSession().removeAttribute("token");
            return "redirect:" + ssoServerUrl + "/login?clientId=" + clientId + "&redirectUri=" + redirectUri;
        }

        // 已登录，显示首页
        model.addAttribute("username", getUsernameFromToken(token));
        return "client1-index";
    }

    // 处理SSO回调（接收令牌）
    // 用于从sso server登录成功后跳转
    @GetMapping("/callback")
    public String callback(String token, HttpServletRequest request) {
        log.info("客户端1回调 token: {}", token);

        if (token != null && validateToken(token)) {
            request.getSession().setAttribute("token", token); // 登录成功，这里在会话里设置token
        }
        return "redirect:/";
    }

    // 调用SSO服务验证令牌
    private boolean validateToken(String token) {
        try {
            String url = ssoServerUrl + "/validate?token=" + token;
            String result = new RestTemplate().getForObject(url, String.class);
            return result.contains("\"valid\":true");
        } catch (Exception e) {
            return false;
        }
    }

    // 从令牌获取用户名（实际应调用SSO服务）
    private String getUsernameFromToken(String token) {
        // 简化处理，实际应调用SSO服务解析
        return "admin";
    }
}
